#include <am.h>
#include <x86.h>

#define RTC_PORT 0x48   // Note that this is not standard
static unsigned long boot_time;

void _ioe_init() {
  boot_time = inl(RTC_PORT);
}

unsigned long _uptime() {
  unsigned long t = inl(RTC_PORT) - boot_time;
  return t;
}

uint32_t* const fb = (uint32_t *)0x40000;

_Screen _screen = {
  .width  = 400,
  .height = 300,
};

extern void* memcpy(void *, const void *, int);

void _draw_rect(const uint32_t *pixels, int x, int y, int w, int h) {
  if (x < 0) x = 0;
  if (y < 0) y = 0;
  if (x + w > _screen.width) w = _screen.width - x;
  if (y + h > _screen.height) h = _screen.height - y;
  
  uint32_t *fb_pos = fb + y * _screen.width + x;  
  // 逐行复制像素数据
  for (int row = 0; row < h; row++) {
    // 计算当前行在源像素数据和目标帧缓冲区中的位置
    const uint32_t *src_row = pixels + row * w;
    uint32_t *dst_row = fb_pos + row * _screen.width;
    memcpy(dst_row, src_row, w * sizeof(uint32_t));
  }
}

void _draw_sync() {
}

int _read_key() {
  uint8_t status = inb(0x64);
    if (status & 0x1) {
        uint32_t key_code = inl(0x60);
        return key_code;
    }
  return _KEY_NONE;
}
